package com.example.helloworld;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class PostBetsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post_bets);
		// Show the Up button in the action bar.
//		setupActionBar();
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
//	private void setupActionBar() {
//		getActionBar().setDisplayHomeAsUpEnabled(true);
//	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.post_bets, menu);
		return true;
	}
//
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		switch (item.getItemId()) {
//		case android.R.id.home:
//			// This ID represents the Home or Up button. In the case of this
//			// activity, the Up button is shown. Use NavUtils to allow users
//			// to navigate up one level in the application structure. For
//			// more details, see the Navigation pattern on Android Design:
//			//
//			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//			//
//			NavUtils.navigateUpFromSameTask(this);
//			return true;
//		}
//		return super.onOptionsItemSelected(item);
//	}
	
	public void displayWinView(View view){
		Intent myIntent = new Intent(this, YouWinActivity.class);
        startActivity(myIntent);
	}
	
	public void postBet(View view){
		// Still not sure how to use dialogs to ensure the user gets an ok/cancel dialog
		// Check to see if the number input is valid
        final EditText postBet = (EditText) findViewById(R.id.postBetText);
        postBet.getText().toString();
        if(postBet.getText().toString().length() == 0){
        	Toast.makeText(getApplicationContext(),  "Invalid bet.", Toast.LENGTH_LONG).show();
        	return;
        }
        // toString() is needed because getText() returns an Editable field instead of a String
        final int betToPost = Integer.parseInt(postBet.getText().toString());
        
        // Start the DB connection on a separate, asynchronous thread
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        PostBet comObject = null;
        // Test to see if the network is actually connected
        if (networkInfo != null && networkInfo.isConnected()) {
        	comObject = new PostBet();
        	// Post the bet using the entered 
        	comObject.execute(betToPost, 1);
        } else {
            Toast.makeText(getApplicationContext(), "No network connection available.", Toast.LENGTH_LONG).show();
        }
        
        // There was some problem downloading bets, so notify the user and exit the method
    	if(comObject == null){
    		Toast.makeText(getApplicationContext(), "There was an error downloading bets.", Toast.LENGTH_LONG).show();
    		return;
    	}
	}
	
	// parameters, progress values, results
	private class PostBet extends AsyncTask<Integer, Integer, Boolean>{
		private static final String url_root = "http://rsl.lib.fit.edu/android_connect/";
		private static final String url_createBet = url_root + "bet_create.php";
		// Necessary JSON variables.
    	private JSONParser jParser = new JSONParser();

		private static final String TAG_MESSAGE = "success";
		private static final String TAG_SUCCESS = "success";
		
		@Override
		protected Boolean doInBackground(Integer... args) {
			// Build parameters
			// Posting a bet only needs the value and the bettor ID
    		List<NameValuePair> params = new ArrayList<NameValuePair>();
    		params.add(new BasicNameValuePair("value", Integer.toString(args[0])));
    		params.add(new BasicNameValuePair("bettorID", Integer.toString(args[1])));
    		// Getting JSON string from URL
    		JSONObject json = jParser.makeHttpRequest(url_createBet, "POST", params);
    		Boolean postResult = false;
    		try {
    			// Check the SUCCESS TAG to see if the http request worked
    			int success = json.getInt(TAG_SUCCESS);
    			if (success == 1) {
    				// Creating the bet was successful
    				postResult = true;
    			}
    		} catch (JSONException e) {
    			e.printStackTrace();
    		}
    		// Return a boolean success result to be used in the onPostExecute() method
    		return postResult;
		}
		
		protected void onPostExecute(Boolean success){
			if(success){
				// Creating the bet was successful
				// Notify the user that the post was successful
				Toast.makeText(getApplicationContext(), "Posting the bet was successful!", Toast.LENGTH_LONG).show();
			}
			else{
				// Was not able to create the bet, notify the user
				Toast.makeText(getApplicationContext(), "Unable to create the bet. Try again.", Toast.LENGTH_LONG).show();
			}
		}
	}
}
